import myCache from '../cache/my-cache.js'

export default {
  namespaced: true,
  
  state:() => ({
    cart: JSON.parse(myCache.getItem('cart') || '[]')
  }),
  
  mutations:{
    //商品添加到购物车
    addToCart(state,goods){
      const findResult = state.cart.find( item => item.goods_id === goods.goods_id)
        if(!findResult){
          state.cart.push(goods)
        }else{
          findResult.goods_count++
        }
        this.commit('m_cart/saveToStorage')
    },
    
    //购物车里的数据存储到本地
    saveToStorage(state){
      myCache.setItem('cart',JSON.stringify(state.cart))
    },
    
    // 更改购物车商品勾选状态
    updateGoodsState(state,goods){
      const findResult = state.cart.find( item => item.goods_id === goods.goods_id)
      if(findResult){
        findResult.goods_state = goods.goods_state
        this.commit("m_cart/saveToStorage")
      }
    },
    
    //更改购物车所有勾选状态（全选和反选）
    updateAllGoodsState(state,newState){
      state.cart.forEach(item => item.goods_state = newState)
      this.commit("m_cart/saveToStorage")
    },
    
    // 更新购物车商品数量
    updateGoodsCount(state,goods){
       const findResult = state.cart.find( item => item.goods_id === goods.goods_id)
       if(findResult){
         findResult.goods_count = goods.goods_count
         this.commit("m_cart/saveToStorage")
       }
    },
    
    // 移除购物车里的商品
    removeGoodsById(state,goods){
      //直接通过过滤器filter来解决
      state.cart = state.cart.filter( item => item.goods_id !== goods.goods_id)
      this.commit("m_cart/saveToStorage")
    },
    
  },
  
  getters:{
    //计算购物车总数
    total(state){
      // let count = 0
      // state.cart.forEach( item => count += item.goods_count)
      // return count
      //通过reduce计算总数
      return state.cart.reduce((total,item) => total += item.goods_count, 0)
    },
    
    //统计购物车中选中的商品总数
    checkedCount(state){
      return state.cart.filter( item => item.goods_state ).reduce((total,item) =>  total += item.goods_count, 0)
    },
    
    //统计购物车中勾选的总价格
    checkedTotalPrice(state){
      return state.cart.filter( item => item.goods_state).reduce((total,item) => total += item.goods_price * item.goods_count, 0).toFixed(2)
    }
  }
}